var mongoose = require('mongoose');
const DataModel = require('../Models/comment.model');

//创建
exports.create = function (req, res, next) {
	const dataModel = new DataModel(req.body);
	dataModel.save()
		.then(data => {
			res.json(data);
		})
}
//获取
exports.get = function (req, res, next) {
	var id = req.params.id;

	DataModel.findById(id, function (err, data) {
		res.json(data);
	})
}

//更新操作
exports.update = function (req, res, next) {
	const id = req.params.id;

	DataModel.findByIdAndUpdate(id, { $set: req.body }, { new: false })//找到就更新，没找到就新增
		.then(data => {
			res.json(data);//返回修改前的数据
		})

}
//删除
exports.remove = function (req, res, next) {
	const id = req.params.id;
	DataModel.findByIdAndRemove(id, function (err, data) {
		res.json(data);
	})
}
//分页
exports.list = function (req, res, next) {
	var page = (req.body.page) ? req.body.page : 1;
	var rows = (req.body.rows) ? req.body.rows : 10;
	//定义查询条件
	var queryCondition = {};
	if (req.body.content && req.body.content.trim().length > 0) {
		content = req.body.content;
		queryCondition = {
			'content': new RegExp(content, 'i')
		}
	}
	if (req.body.belongId && req.body.belongId.trim().length > 0) {
		belongId = req.body.belongId;
		queryCondition = Object.assign(queryCondition, {
			'belongId':belongId
		})
	}
	DataModel.paginate(queryCondition, { sort: { _id: -1 }, page: parseInt(page), limit: parseInt(rows) },
		function (err, result) {
			result.rows = result.docs;
			delete result.docs;
			res.json(result)
		});
}
//多个删除
exports.deletes = function (req, res, next) {
	const ids = req.body.ids;
	if (ids.length > 0) {
		DataModel.remove({ _id: { $in: ids.split(',') } })
			.then(data => {
				res.json({ "msg": "deletes success", "status": 200 });
			})
	} else {
		res.json({ "msg": "deletes fail", "status": 404 });
	}
}